package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AddressBookServiceImpl implements AddressBookService {

    @Autowired
    private AddressBookMapper addressBookMapper;

    /**
     * 查询当前登录用户的所有地址信息
     *
     * @return
     */
    @Override
    public List<AddressBook> list() {
        //获取用户id
        Long userId = BaseContext.getCurrentId();
        List<AddressBook> addressBookList = addressBookMapper.list(userId);
        return addressBookList;
    }

    /**
     * 新增地址
     *
     * @param addressBook
     */
    @Override
    public void save(AddressBook addressBook) {
        //将当前登录的用户id添加
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(0);
        addressBookMapper.save(addressBook);
    }

    /**
     * 根据地址id查询地址
     *
     * @param id
     * @return
     */
    @Override
    public AddressBook getByid(Long id) {
        AddressBook addressBook = addressBookMapper.getByid(id);
        return addressBook;
    }


    /**
     * 根据地址id修改地址
     *
     * @param addressBook
     */
    @Override
    public void updateById(AddressBook addressBook) {
        addressBookMapper.updateById(addressBook);
    }

    /**
     * 设置地址
     *
     * @param addressBook
     */
    @Override
    public void setDefault(AddressBook addressBook) {
        //1.将当前用户的所有地址设置成非默认地址
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(0);
        addressBookMapper.setNoDefault(addressBook);

        //2.把当前地址设置成默认地址
        addressBook.setIsDefault(1);
        addressBookMapper.updateById(addressBook);
    }


    /**
     * 根据id删除地址
     *
     * @param id
     */
    @Override
    public void deleteByid(Long id) {
        addressBookMapper.deleteById(id);
    }

    /**
     * 查询默认地址
     *
     * @param addressBook
     * @return
     */
    @Override
    public AddressBook getDefaultAddress(AddressBook addressBook) {
        addressBook = addressBookMapper.getDefaultAddress(addressBook);
        return addressBook;
    }
}
